#-*- coding: UTF-8 -*-
import threading
from multiprocessing import Process,Queue
from multiprocessing import Pool
import os,time,random
# 多进程模式；
# 多线程模式；
# 多进程+多线程模式。
# 子进程要执行的代码
'''             多进程*******多进程             '''
# def run_proc(name):
#     print '子进程 %s (%s)...' % (name, os.getpid())
#
# if __name__ == '__main__':
#     print '父进程 %s.' % os.getpid()
#     p = Process(target=run_proc, args=('测试',))
#     print 'Process will start.'
#     p.start()
#     p.join()
#     print 'Process end.'
#     print '----------------------'
# def long_time_task(name):
#     print 'Run task %s (%s).'%(name,os.getpid())
#     time1 = time.time()
#     time.sleep(random.random()*3)
#     time2 = time.time()
#     print 'Task %s runs %0.2f seconds'%(name,(time2-time1))
# if __name__ == '__main__':
#     print 'Parent process %s.'% os.getpid()
#     # p = Pool()  # pool（）默认进行4个进程
#     p = Pool(8)  # 同时进行8个进程 d电脑CPU核数而定
#     for i in range(16):
#         # p.apply(long_time_task, args=(i,))
#         #  apply 是阻碍的、等待子进程完成后进行下一个
#         p.apply_async(long_time_task,args=(i,))
#     print "等待所有进程完成"
#     p.close()
#     p.join()
#     print '所有进程已完成'
#     print '----------------------'
# def write(q):
#     for value in['A','V','B','C','M','P']:
#         print 'Put %s to M...'% value
#         q.put(value)
#         time.sleep(random.random())
# def read(q):
#     while True:
#         value =q.get(True)
#         print 'Get %s from M.' % value
# if __name__ == '__main__':
#     # 父进程创建Queue，并传给各个子进程：
#     q = Queue()
#     pw = Process(target=write, args=(q,))
#     pr = Process(target=read, args=(q,))
#     # 启动子进程pw，写入:
#     pw.start()
#     # 启动子进程pr，读取:
#     pr.start()
#     # 等待pw结束:
#     pw.join()
#     # pr进程里是死循环，无法等待其结束，只能强行终止:
#     pr.terminate()
#     print '----------------------'

#
# def loop():
#     print 'threading %s is running...' % threading.current_thread().name
#     i = 0
#     while i < 6:
#         i= i+1
#         print 'thread  %s ---> %s' % (threading.current_thread().name,i)
#         time.sleep(1)
#     print 'thread %s ended' % threading.current_thread().name
# print 'threading %s is running...' % threading.current_thread().name
# m = threading.Thread(target = loop, name='LoopThread')
# m.start()
# time0 = time.time()
# m.join()
# print 'thread %s ended.' % threading.current_thread().name
# time1 = time.time()
# time = time1 - time0
# print "运行时间 %s：" % time
#

# 全局变量加锁
# balance = 0
# def change_it(i):
#     global balance
#     balance = balance + i
#     balance = balance - i
# def run_thread(i):
#     for i in range(100):
#         change_it(i)
# t1 = threading.Thread(target=run_thread,args=(510,))
# t2 = threading.Thread(target=run_thread,args=(100,))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print balance
# print '----------'
#
# balance1 = 0
# lock = threading.Lock
# def change_it(n):
#     global balance1
#     balance1 = balance1 + n
#     balance1 = balance1 - n
# def run_thread(n):
#     for i in range(100):
#         MX.acquire()
#         try:
#             change_it(n)
#         finally:
#             pass
#         MX.release()
# MX = threading.Lock()
# m1=threading.Thread(target=run_thread,args=(5100,))
# m2=threading.Thread(target=run_thread,args=(1000,))
# m1.start()
# m2.start()
# m1.join()
# m2.join()
# print balance1

#
# class MyThread(threading.Thread):
#     def __init__(self):
#         threading.Thread.__init__(self)
#     def run(self):
#         global n, lock
#         time.sleep(1)
#         if lock.acquire():
#             print n, self.name
#             n += 1
#             lock.release()
# if "__main__" == __name__:
#     n = 1
#     ThreadList = []
#     lock = threading.Lock()
#     for i in range(1, 200):
#         t = MyThread()
#         ThreadList.append(t)
#     for t in ThreadList:
#         t.start()
#     for t in ThreadList:
#         t.join()
# print '----------'
# # Threadlocal
# # 创建全局ThreadLocal对象:
# local_school = threading.local()
#
# def process_student():
#     # 获取当前线程关联的student:
#     std = local_school.student
#     print('Hello, %s : %s' % (std, threading.current_thread().name))
#     print threading.current_thread().getName()
# def process_thread(name):
#     # 绑定ThreadLocal的student:
#     local_school.student = name
#     process_student()
#
# t1 = threading.Thread(target = process_thread, args=('Alice',), name='A-线程')
# t2 = threading.Thread(target = process_thread, args=('Bob',), name='B-线程')
# t1.start()
# t2.start()
# t1.join()
# t2.join()

class myThread(threading.Thread):
    def __int__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID = threadID()
        self.name = name()
        self.counter = counter()
    def run(self):
        print "Star..." + self.name
        AAA.acquire()
        print1(self.name,self.counter,6)
        AAA.release()
def print1(threadingname,delary,counter):
    while counter:
        print "%s:%s" % (threadingname,time.ctime(time.time()))
        time.sleep(delary)
        counter -= 1
AAA = threading.Lock()
threads = []
thread1 = myThread(1,'Thread-1',1)
thread2 = myThread(2,'thread-2',2)
thread3 = myThread(3,'thread-3',3)
thread4 = myThread(4,'thread-4',4)
for i in threads:
    i.start()
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)
threads.append(thread4)
for t in threads:
    t.join()
print 'end...'
